#include<stdio.h>
#include"homework43.h"
int a[100];
int i=0;
void pf()
{
	int n;
	for(n=0;n<i;n++)
	printf("%-4d",a[n]);
}
int getarray()
{
	FILE *fp;
	fp=fopen("insort.txt","r");
	if(fp==NULL) 
		return -1;
	while(fscanf(fp,"%d",&a[i])!=EOF) 
		i++;
	fclose(fp);
	return i;
}
void writearray()
{
	int n;
	FILE *fp;
	fp=fopen("insort.txt","w");
	for(n=0;n<i;n++)
	fprintf(fp,"%d ",a[n]);
	fclose(fp);
 } 
int BinarySearch(int *a,int key,int low,int high)
{
	int mid;
    if(low>high)
        return -1;
    mid=(low+high)/2;
    if(a[mid]==key)
		return mid;
    else if(a[mid]>key)
        {
        	if(a[mid-1]>key)
			return BinarySearch(a,key,low,mid-1);
			else return mid;
		}
    	else
    	{
    		if(a[mid+1]<key)
			return BinarySearch(a,key,mid+1,high);
			else return mid+1;
  		}
}
void insert(int num)
{
	int n,flag;
	if(a[0]>=num)
	{
		for(n=i;n>0;n--)
			a[n]=a[n-1];
		a[0]=num;
	}
	else if(num>=a[i-1])
		{
			a[i]=num;
		}
		else 
		{
			flag=BinarySearch(a,num,0,i-1);
			for(n=i;n>flag;n--)
				a[n]=a[n-1];
			a[flag]=num;
		}
	i++;
}
